package sunwin.yoms.web.comm;

import jodd.jerry.Jerry;
import jodd.jerry.JerryFunction;
import jodd.util.StringUtil;
import sunwin.yoms.comm.Base64FileHelper;
import sunwin.yoms.comm.FileHelper;
import sunwin.yoms.comm.model.NameAndValueModel;
import sunwin.yoms.service.comm.YomsDefaultData;

import java.io.File;

/**
 * Created by mt on 2015-8-23.
 */
public class YomsBase64Image {

    /**
     * 将base64编码还原到img src中
     *
     * @param base64code
     * @return
     */
    public static String restoreBase64code(String base64code) {
        return String.format("<img src=\"%s\" >", base64code);
    }

    /**
     * 获取img src属性
     *
     * @param img
     * @return
     */
    public static String getSrcValue(String img) {
        Jerry.JerryParser jerryParser = new Jerry.JerryParser();
        Jerry doc = jerryParser.parse(img);
        return doc.$("img").attr("src");
    }

    /**
     * 将img标签中src base64编码转换为文件路径
     */
    public static NameAndValueModel recompileImgSrc(String content, final int id, final String folder) {
        NameAndValueModel imgAndContent = new NameAndValueModel();
        final String contentPath = "img/" + folder + "/";

        Jerry.JerryParser jerryParser = new Jerry.JerryParser();
        Jerry doc = jerryParser.parse(content);

        final File file = new File(YomsDefaultData.WebRoot, contentPath + id);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        File tempfile = new File(YomsDefaultData.WebRoot, contentPath + id + ".temp");
        if (!tempfile.exists() && !tempfile.isDirectory()) {
            tempfile.mkdir();
        }

        doc.$("img").each(new JerryFunction() {
            @Override
            public boolean onNode(Jerry $this, int index) {
                index = index + 1;
                try {

                    NameAndValueModel navm = recompileImgSrc($this.attr("src"));
                    String src = navm.getValue();
                    String suffix = navm.getName();

                    Base64FileHelper.decoderBase64File(src, file.getPath() + ".temp/" + index + "." + suffix);
                    $this.attr("src", contentPath + id + "/" + index + "." + suffix);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        FileHelper.delFolder(file.getPath() + "/");
        FileHelper.rename(file.getPath() + ".temp", file.getPath());
        imgAndContent.setValue(doc.html());
        return imgAndContent;
    }

    /**
     * 重新编译html img标签src属性
     *
     * @param src
     * @return
     */
    private static NameAndValueModel recompileImgSrc(String src) {
        NameAndValueModel suffixAndSrc = new NameAndValueModel();

        if (src.substring(0, 4).equals("img/")) {
            //获取文件后缀名
            String suffix = src.substring(src.lastIndexOf(".") + 1);
            //获取文件类型
            String fileType = "image";
            //拼装base64头
            String head = String.format("data:%s/%s;base64,", fileType, suffix);

            String base64FilePath = new File(YomsDefaultData.WebRoot, src).getAbsolutePath();
            String base64 = null;
            try {
                base64 = Base64FileHelper.encodeBase64File(base64FilePath);
                src = head + base64;
            } catch (Exception e) {
                e.printStackTrace();
                src = null;
            }
        }

        if (StringUtil.isNotBlank(src) && src.contains("data:")) {
            //获取文件头
            String head = src.substring(0, src.indexOf(",") + 1);
            //获取文件类型
            String fileType = head.substring(src.indexOf(":") + 1, src.indexOf("/"));
            //获取文件后缀名
            String suffix = head.substring(src.indexOf("/") + 1, src.indexOf(";"));
            if (suffix.contains("icon") && suffix.equals("x-icon")) {
                suffix = "ico";
            }
            //删除头
            src = src.replaceAll(head, "");

            suffixAndSrc.setName(suffix);
            suffixAndSrc.setValue(src);
        } else {
            suffixAndSrc.setValue("");
            suffixAndSrc.setName("");
        }

        return suffixAndSrc;
    }
}
